﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ReadTxtAndWriteXml
{
    class Program
    {
        public Program()
        {

        }
        const string dllname = "c.dll";
        [DllImport(dllname, EntryPoint = "??0COptical_para_cal_fun@@QAE@XZ")]
        public static extern Double ViewCalCu(System.Double begin, System.Double end);

        static void Main(string[] args)
        {
            var math = ViewCalCu(3, 100);
            Console.Write(math + "11111");
            StreamReader sr = new StreamReader("C:\\Users\\Admin\\Desktop\\Personal\\demo\\ReadTxtAndWriteXml\\CN.txt");///获取txt文件流
            StringBuilder sb = new StringBuilder(" <?xml version=\"1.0\" encoding=\"utf - 8\"?>\n<root>\n");///拼接根节点
            string Data = sr.ReadToEnd();//全部读取完毕
            string[] strarr = Regex.Split(Data, "\r\n", RegexOptions.IgnoreCase);//分割出每一行
            //string[] Oneofarr = strarr[0].Split(',');//再把每一行分割     【0】是name 【1】是comment [2]是value  
            for (int i = 0; i < strarr.Length; i++)
            {
                string[] temparr = strarr[i].Split(',');///分割每行的每个元素长度为五，但后两个没用 忽略
                sb.Append("<data name=\"" + temparr[0] + "\" xml:space=\"preserve\">\n" + "<value>" + temparr[2] + "</value>\n" + "<comment>" + temparr[1] + "</comment>\n</data>\n");
            }
            sb.Append("</root>");//最后价格结尾
            string Alldata = sb.ToString();//转换为普通字符串
            WriteToFile("结果文件.xml", Alldata, false);//调用写方法写出文件
            Console.WriteLine("完成！");
            Console.WriteLine("完成！");
            Console.ReadKey();///别关
        }
        public static void WriteToFile(string name, string content, bool isCover)///参数说明奥  看清楚干啥的   name文件名  content文件内容，就是那个大字符串 iscover是判断是否有重复文件
        {
            FileStream fs = null;//空文件流
            try
            {
                if (!isCover && File.Exists(name))//判断是否替换，替换！
                {
                    fs = new FileStream(name, FileMode.Append, FileAccess.Write);//追加流数据
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);//追加编码格式
                    sw.WriteLine(content);//根据格式和数据写进去
                    sw.Flush();//托段
                    sw.Close();//关闭连接节省内存
                    System.IO.File.WriteAllText(@"C:\Users\Admin\Desktop\Personal\demo\ReadTxtAndWriteXml\结果.txt", content, System.Text.Encoding.UTF8);///写入到指定文件夹下
                }
                else
                {
                    File.WriteAllText(name, content, Encoding.UTF8);//否则再调用一次
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();//直接关闭 节省电脑资源
                }
            }
        }
    }
}
